﻿using System;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows.Controls;
using System.Windows.Printing;
using MedLink2011.Core;
using MedLink2011.Views.Patients.ChildWindows;
using MedLink2011.Views.Patients.Reports;
using MedLink2011.Web.Models;
using MedLink2011.Web.Services;
using System.Collections.ObjectModel;
using System.Windows;
using Telerik.Windows.Controls.GridView;
using RelayCommand = MedLink2011.Core.RelayCommand;
using System.Windows.Browser;
using MedLink2011.Controls;

namespace MedLink2011.Views.Patients.ViewModels
{
    public class Inpatient_regViewModel : PerformAsyncQueryBase // the AsyncQuery one inherits from ViewModel Base
    {
        public static MedLink2011Context _inpatient_regContext;
        private ObservableCollection<Inpatient_reg> _inpatient_reg;
        private MedLink2011Context _context;
        private EntityQuery<MedLink2011.Web.Models.Hospital_bed> _hospitalBedQuery;
        private EntityQuery<MedLink2011.Web.Models.Patient> _patientQuery;
        //
       public Inpatient_regViewModel()
        {
            if (!IsDesignTime)
            {
                _inpatient_regContext = new MedLink2011Context();
                IsBusy = true;
                WireCommands();
                LoadInpatient_regAsync();
                LoadComboBoxData();
            }
        }
        
        #region "Load Current Inpatient_reg"
        readonly int loadedPatient_Id = MedLink2011.Views.Patients.ViewModels.PatientViewModel.DashLoad_PK;
        //readonly int loadedPatient_Id = 1;
        private void LoadInpatient_regAsync()
         {
           if (!_inpatient_regContext.IsSubmitting)
            {
                if (loadedPatient_Id > 0)
                {
                    PerformAsyncQuery<Inpatient_reg>(_inpatient_regContext, _inpatient_regContext.GetInpatient_regsForPatientsQuery(loadedPatient_Id), Inpatient_regLoadedComplete);
                }
                else
                {
                    PerformAsyncQuery<Inpatient_reg>(_inpatient_regContext, _inpatient_regContext.GetInpatient_regsQuery(), Inpatient_regLoadedComplete); 
                }
            }
        }

        private EntitySet<Inpatient_reg> _inpatient_regCollection;
        public EntitySet<Inpatient_reg> Inpatient_regCollection
        {
            get { return _inpatient_regCollection; }
            set
            {
                _inpatient_regCollection = value;
                RaisePropertyChanged("Inpatient_regCollection");
            }
        }

        private Inpatient_reg _currentInpatient_reg;
        public Inpatient_reg CurrentInpatient_reg
        {
            get { return _currentInpatient_reg; }
            set
            {
                _currentInpatient_reg = value;
                RaisePropertyChanged("CurrentInpatient_reg");
            }
        }

        #endregion "Load Current Inpatient_reg"

        #region Commands

        private void EnableCommands()
        {
            AddNewInpatient_regCommand.IsEnabled = true;
            SaveInpatient_regCommand.IsEnabled = true;
            DeleteInpatient_regCommand.IsEnabled = true;
            PrintInpatient_regCommand.IsEnabled = true;
            SearchInpatient_regCommand.IsEnabled = true;
            SelectionChangedCommand.IsEnabled = true;
            RowLoadedCommand.IsEnabled = true;
            ShowChartDashboardCommand.IsEnabled = true;
           }

        private void WireCommands()
        {
            AddNewInpatient_regCommand = new RelayCommand(AddInpatient_reg);
            SaveInpatient_regCommand = new RelayCommand(SaveInpatient_reg);
            DeleteInpatient_regCommand = new RelayCommand(DeleteInpatient_reg);
            PrintInpatient_regCommand = new RelayCommand(PrintInpatient_reg);
            ShowChartDashboardCommand = new RelayCommand<object>(ShowChartDashboard);
            SearchInpatient_regCommand = new RelayCommand<string>(SearchInInpatient_reg);
            SelectionChangedCommand = new RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs>(e =>
            {
                var element = e.OriginalSource as UIElement;
                var element2 = e.OriginalSource as Telerik.Windows.Controls.DataControl;

                if ((element2 != null) && (!_toDelete))
                {
                    var _theItem = element2.SelectedItem;
                    CurrentInpatient_reg = (Inpatient_reg) _theItem;
            SelectedHospitalBed =
                HospitalBedCollection.Where(c => c.Hospital_bed_Id == CurrentInpatient_reg.Hospital_bed_Id).SingleOrDefault();
            SelectedPatient =
                PatientCollection.Where(c => c.Patient_Id == CurrentInpatient_reg.Patient_Id).SingleOrDefault();
              }
            });
            
            RowLoadedCommand = new RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs>( e =>
                {
                    if (e.Row is GridViewRow && !(e.Row is GridViewNewRow))
                    {
                        MedLink2011.Web.Models.Inpatient_reg model = e.DataElement as MedLink2011.Web.Models.Inpatient_reg;
                        var grid = new Grid();
                        var tb = new TextBlock
                               {
                               Text = string.Format(
			"Nursing Plan : {0} \r\n"+
			"Info : {1} \r\n"+
			"Admission Reason : {2} \r\n"+
			"Operating Physician : {3} \r\n"+
			"Admission Type : {4} \r\n"+
			"Hospitalization Date : {5} \r\n"+
			"Attending Physician : {6} \r\n"+
			"Discharge Plan : {7} \r\n"+
			"State : {8} \r\n"+
			"Discharge Date : {9} \r\n",

			model.Nursing_Plan,
			model.Info,
			model.Admission_Reason,
			model.Operating_Physician,
			model.Admission_Type,
			model.Hospitalization_Date,
			model.Attending_Physician,
			model.Discharge_Plan,
			model.State,
			model.Discharge_Date
                     ),
                            Margin = new Thickness(3, 3, 3, 3),
                            Opacity = 0.8,
                            MaxWidth = 250,
                            FontSize = 10,
                            TextWrapping = TextWrapping.NoWrap
                                     };
                        grid.Children.Add(tb);
                        ToolTipService.SetToolTip(e.Row, grid);
                    }
                });
                
           }

        public RelayCommand<Telerik.Windows.Controls.GridView.RowLoadedEventArgs> RowLoadedCommand
        {
            get;
            private set;
        }

        public RelayCommand<Telerik.Windows.Controls.SelectionChangeEventArgs> SelectionChangedCommand
        {
            get;
            private set;
        }

        public RelayCommand AddNewInpatient_regCommand
        {
            get;
            private set;
        }
        public RelayCommand SaveInpatient_regCommand
        {
            get;
            private set;
        }
        public RelayCommand DeleteInpatient_regCommand
        {
            get;
            private set;
        }
        public RelayCommand PrintInpatient_regCommand
        {
            get;
            private set;
        }

        public RelayCommand<object> ShowChartDashboardCommand
        {
            get;
            private set;
        }

        public RelayCommand<string>  SearchInpatient_regCommand
        {
            get;
            private set;
        }

        #endregion Commands
        
        private void SearchInInpatient_reg( string searchText)
        {
            MessageBox.Show(searchText);
        }
        
        private void SaveInpatient_reg()
        {
            CurrentInpatient_reg.Hospital_bed_Id = SelectedHospitalBed.Hospital_bed_Id;
            CurrentInpatient_reg.Patient_Id = SelectedPatient.Patient_Id;
            CurrentInpatient_reg.write_date = CurrentTime;
            CurrentInpatient_reg.write_uid = CurrentUser;
            _inpatient_regContext.SubmitChanges(p =>
            {
                if (p.HasError)
                {
                    p.MarkErrorAsHandled();
                    ErrorWindow.CreateNew(p.Error);
                }
                else
                {
                    MessageBox.Show("Inpatient_reg se ha actualizado");
                    RaisePropertyChanged("Inpatient_regCollection");
                    RaisePropertyChanged("CurrentInpatient_reg");
                }
            }, null);
        }
        #region "Add New"
        //http://forums.silverlight.net/forums/p/193377/449256.aspx
        private void AddInpatient_reg()
        {

            MedLink2011.Web.Models.Inpatient_reg inpatient_reg = new MedLink2011.Web.Models.Inpatient_reg();
            Inpatient_regsAddCW addNewWindow = new Inpatient_regsAddCW();
            addNewWindow.DataContext = inpatient_reg;
            addNewWindow.Closed += (s, ee) =>
            {
                if (addNewWindow.DialogResult == true)
                {
                    inpatient_reg.create_date = CurrentTime;
                    inpatient_reg.write_date = CurrentTime;
                    inpatient_reg.create_uid = CurrentUser;
                    inpatient_reg.write_uid = CurrentUser;
                    
                    _inpatient_regContext.Inpatient_regs.Add(inpatient_reg);
                    _inpatient_regContext.SubmitChanges(p =>
                    {
                        if (p.HasError)
                        {
                            p.MarkErrorAsHandled();
                            ErrorWindow.CreateNew(p.Error);
                        }
                        else
                        {
                            MessageBox.Show("New Inpatient_reg has been added");
                        }
                    }, null);
                }
            };
            addNewWindow.Show();
            addNewWindow.Closed += FrmClosedAdd;
        }


        void FrmClosedAdd(object sender, EventArgs e)
        {
            LoadInpatient_regAsync();
        }
        #endregion "Add New"


        private static int _dashload_PK;
        public static int DashLoad_PK
        {
            get { return _dashload_PK; }
            set { _dashload_PK = value ; }
        }


        private void ShowChartDashboard(object selectedItem)
        {
            //
            string a = selectedItem.ToString();
            int i = a.IndexOf(":") + 1;
            a = a.Substring(i);
            int dashLoadPk;
            int.TryParse(a, out dashLoadPk);
            DashLoad_PK = dashLoadPk;
            Uri target = new Uri("/Patients/Pages/PatientsTitlePage?Inpatient_reg_Id=" + DashLoad_PK, UriKind.Relative);

   
            var _theItem = selectedItem;
            CurrentInpatient_reg = (Inpatient_reg)_theItem;
            //NavigationService.Navigate(target);
            //var service = ((Page)((App)Application.Current).RootVisual).NavigationService;
            //if (service != null) service.Navigate(target);
        }



        private static int _current_Patient_id;
        public static int Current_Patient_id
        {
            get { return _current_Patient_id; }
            set { _current_Patient_id = value ; }
        }
        
        private bool _isBusy;
        public bool IsBusy
        {
            get { return _isBusy; }
            set
            {
                _isBusy = value;
                RaisePropertyChanged("IsBusy");
            }
        }
        public string CurrentTime
        {
            get
            {
                DateTime time = DateTime.Now;   
                const string format = "MMM ddd d HH:mm yyyy";  
                return (time.ToString(format));
            }
        }

        public string CurrentUser
        {
            get { return WebContext.Current.User.ToString() ; }
        }


        #region "LoadComboBoxData"


        public EntitySet<Hospital_bed> HospitalBedCollection { get; set; }
        private Hospital_bed _selectedHospitalBed;
        public Hospital_bed SelectedHospitalBed
        {
            get { return _selectedHospitalBed; }
            set
            {
                _selectedHospitalBed = value;
                RaisePropertyChanged("SelectedHospitalBed");
            }
        }
            
        public EntitySet<Patient> PatientCollection { get; set; }
        private Patient _selectedPatient;
        public  Patient SelectedPatient
        {
            get { return _selectedPatient; }
            set
            {
                _selectedPatient = value;
                RaisePropertyChanged("SelectedPatient");
            }
        }
        private long dtStart = 0;
        private long dtEnd = 0;
        void LoadComboBoxData()
        {
            dtStart = System.DateTime.Now.Ticks;
            
            //Hospital_bed_IdComboBox
            _context = new MedLink2011Context();
            _hospitalBedQuery = _context.GetHospital_bedQuery();
            _hospitalBedQuery = _hospitalBedQuery.OrderBy(e => e.Hospital_bed_Id);
            PerformAsyncQuery<Hospital_bed>(_context, _hospitalBedQuery, Hospital_bed_IdComboBoxLoaded);
            HospitalBedCollection = _context.Hospital_beds;
            
            //Patient_IdComboBox
            _context = new MedLink2011Context();
            _patientQuery = _context.GetPatientsQuery();
            _patientQuery = _patientQuery.OrderBy(e => e.Patient_Id);
            PerformAsyncQuery<Patient>(_context, _patientQuery, Patient_IdComboBoxLoaded);
            PatientCollection = _context.Patients;
        }

        private void Hospital_bed_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Hospital_bed> e)
        {
            if (!e.HasError)
            {
                SelectedHospitalBed =
                    HospitalBedCollection.Where(c => c.Hospital_bed_Id == CurrentInpatient_reg.Hospital_bed_Id).SingleOrDefault();
            }
        }
        private void Patient_IdComboBoxLoaded(object sender, MedLink2011.Core.EntityResultsArgs<Patient> e)
        {
            if (!e.HasError)
            {
                SelectedPatient =
                    PatientCollection.Where(c => c.Patient_Id == CurrentInpatient_reg.Patient_Id).SingleOrDefault();
            }
        }


        private void Inpatient_regLoadedComplete(object sender, MedLink2011.Core.EntityResultsArgs<Inpatient_reg> e)
        {
            IsBusy = false;
            if (!e.HasError)
            {
                Inpatient_regCollection = _inpatient_regContext.Inpatient_regs;
                CurrentInpatient_reg = Inpatient_regCollection.FirstOrDefault();
                EnableCommands();
            SelectedHospitalBed = HospitalBedCollection.Where(c => c.Hospital_bed_Id == CurrentInpatient_reg.Hospital_bed_Id).SingleOrDefault();
            SelectedPatient = PatientCollection.Where(c => c.Patient_Id == CurrentInpatient_reg.Patient_Id).SingleOrDefault();

            }
            else
            {
                // notify user if there is any error
                //AppMessages.RaiseErrorMessage.Send(e.Error);
            }
        }

        private void AddNewForm_Closed(object sender, MedLink2011.Core.EntityResultsArgs<Inpatient_reg> e)
        {
            if (!e.HasError)
            {
                
            }
        }


        #endregion "LoadComboBoxData"

        #region "Delete"

        private bool _toDelete=false;

        private void DeleteInpatient_reg()
        {
            _toDelete = true;
            var inpatient_regToDelete = CurrentInpatient_reg;
           if (inpatient_regToDelete != null)
                    {
                     var result = MessageBox.Show("Are you sure you wish to delete the Current Inpatient_reg?", "Confirm Delete", MessageBoxButton.OKCancel);
                      if (result.Equals(MessageBoxResult.OK))
                        {
            _inpatient_regContext.Inpatient_regs.Remove(inpatient_regToDelete);
            _inpatient_regContext.SubmitChanges(o =>
            {
                if (o.HasError)
                {
                    MessageBox.Show("Esta inpatient_reg no se puede eliminar ya que existen datos que dependen de esta Inpatient_reg.....", "Cancelado", MessageBoxButton.OKCancel);
                    o.MarkErrorAsHandled();
                    _inpatient_regContext.RejectChanges();
                }
                else
                {
                    MessageBox.Show("el registro de  inpatient_reg ha sido eliminado exitosamente ... ");
                    //LoadInpatient_regAsync();
                    RaisePropertyChanged("Inpatient_regCollection");
                    CurrentInpatient_reg = Inpatient_regCollection.FirstOrDefault();
                }
            }, null);
            }
       }
            _toDelete = false;
        }
        #endregion "Delete"
        
        #region "Print"
        
        private void PrintInpatient_reg()
        {
            if (CurrentInpatient_reg != null)
            {
                PrintDocument document = new PrintDocument();
                document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage); // fires when every single page is going to print 
                document.EndPrint += new System.EventHandler<EndPrintEventArgs>(document_EndPrint); // when printing is completed
                string PrintQueue = "Inpatient_regs_" + CurrentInpatient_reg.ToString(); // to show in the print queue
                document.Print(PrintQueue); //fires when printing has begun
            }
        }
        
        static void document_EndPrint(object sender, EndPrintEventArgs e)
        {
            if (e.Error != null)
            {
                ErrorWindow error = new ErrorWindow(e.Error.Message, e.Error.StackTrace);
            }
            else
                MessageBox.Show("Print Complete");
        }
        
        void document_PrintPage(object sender, PrintPageEventArgs e)
        {
            PrintDocument document = sender as PrintDocument;
            MedLink2011.Web.Models.Inpatient_reg appt = CurrentInpatient_reg as MedLink2011.Web.Models.Inpatient_reg;
            if (appt != null)
            {
                //e.HasMorePages = appt.ChildEntity != null && document.PrintedPageCount < appt.ChildEntity.Count;
                //if (document.PrintedPageCount > 0)
                //{
                // e.PageVisual = new ChildEntityFReport() { DataContext = appt.ChildEntity.ElementAt(document.PrintedPageCount - 1) };
                //}
                //else
                e.PageVisual = new Inpatient_regsFReport() { DataContext = appt };
            }
        }
       
        #endregion "Print"

    }


}

